package com.ctshk.rpc.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.mian.data.MainDataSubjectDTO;
import com.ctshk.rpc.system.entity.MainDataSubject;
import com.ctshk.rpc.system.mapper.MainDataSubjectMapper;
import com.ctshk.rpc.system.req.main.data.MainDataSubjectAddReq;
import com.ctshk.rpc.system.req.main.data.MainDataSubjectListReq;
import com.ctshk.rpc.system.service.IMainDataSubjectService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 主数据 - 科目 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-06-22
 */
@DubboService
public class MainDataSubjectServiceImpl extends ServiceImpl<MainDataSubjectMapper, MainDataSubject> implements IMainDataSubjectService {

    @Autowired
    private MainDataSubjectMapper mainDataSubjectMapper;



    /**
     * 列表
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<MainDataSubjectDTO> list(MainDataSubjectListReq req) {
        Page<MainDataSubject> page = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<MainDataSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getName()),"name",req.getName());
        queryWrapper.like(StringUtils.isNotBlank(req.getNumber()),"number",req.getNumber());
        queryWrapper.eq(req.getBusinessType() != null,"business_type",req.getBusinessType());
        queryWrapper.eq(req.getType() != null,"type",req.getType());
        queryWrapper.eq(req.getStatus() != null,"status",req.getStatus());
        queryWrapper.eq("is_deleted",0);
        queryWrapper.orderByDesc("gmt_create");
        Page<MainDataSubject> result = mainDataSubjectMapper.selectPage(page, queryWrapper);
        List<MainDataSubject> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), result.getCurrent() == 1, result.getTotal() <= (result.getCurrent() * result.getSize()), result.getTotal(), result.getCurrent(), result.getSize());
        }
        List<MainDataSubjectDTO> list = EntityUtil.copyList(records,MainDataSubjectDTO.class);
        return new PageResponse<>(list,
                result.getCurrent() == 1,
                result.getTotal() <= (result.getCurrent() * result.getSize()),
                result.getTotal(), result.getCurrent(), result.getSize());
    }

    /**
     * 新增/修改
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(MainDataSubjectAddReq req, Long userId) {
        MainDataSubject subject = EntityUtil.copy(req,MainDataSubject.class);
        LocalDateTime now = LocalDateTime.now();
        boolean result = false;
        if (req.getId() == null){
            MainDataSubjectDTO dto = mainDataSubjectMapper.queryByCondition(req.getBusinessType(), req.getCollectionType());
            if (dto != null){
                return Result.failed(new BusinessException(SystemError.MAINDATA_4029));
            }
            //新增
            subject.setId(SnowflakeIdWorker.nextId());
            subject.setStatus(0);
            subject.setCreateId(userId);
            subject.setGmtCreate(now);
            subject.setIsDeleted(0);
            result = save(subject);
        }else{
            //修改
            subject.setModifiedId(userId);
            subject.setGmtModified(now);
            result = updateById(subject);
        }
        if (!result){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success(subject.getId());
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public Result<MainDataSubjectDTO> detail(Long id) {
        MainDataSubject subject = getById(id);
        if (subject == null || Objects.equals(subject.getIsDeleted(),1)){
            return Result.failed(new BusinessException(SystemError.SYS_411));
        }
        MainDataSubjectDTO dto = EntityUtil.copy(subject,MainDataSubjectDTO.class);
        return Result.success(dto);
    }

    /**
     * 修改状态
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result status(Long id, Long userId) {
        MainDataSubject subject = getById(id);
        if (subject == null || Objects.equals(subject.getIsDeleted(),1)){
            return Result.failed(new BusinessException(SystemError.SYS_411));
        }
        int status = subject.getStatus().intValue() == 1?0:1;
        subject.setStatus(status);
        subject.setGmtCreate(LocalDateTime.now());
        subject.setModifiedId(userId);
        boolean update = updateById(subject);
        if (!update){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success(subject.getId());
    }

    /**
     * 删除
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(Long id, Long userId) {
        MainDataSubject subject = getById(id);
        if (subject == null || Objects.equals(subject.getIsDeleted(),1)){
            return Result.failed(new BusinessException(SystemError.SYS_411));
        }
        subject.setIsDeleted(1);
        subject.setGmtCreate(LocalDateTime.now());
        subject.setModifiedId(userId);
        boolean update = updateById(subject);
        if (!update){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success(subject.getId());
    }

    /**
     * 根据业务类型查询（内部接口）
     *
     * @param businessType
     * @param collectionType
     * @return
     */
    @Override
    public MainDataSubjectDTO queryByCondition(Integer businessType, Integer collectionType) {
        if (businessType == null || collectionType == null){
            return null;
        }
        MainDataSubjectDTO dto = mainDataSubjectMapper.queryByCondition(businessType, collectionType);
        if (dto != null && Objects.equals(dto.getStatus(),0)){
            return dto;
        }
        return null;
    }

}
